package com.birds.portal.db;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DataBase {

	static Properties properties;
	static Connection connection;
	PreparedStatement statement = null;

	public DataBase() {
	}

	static {
		properties = new Properties();
		try {
			properties.load(DataBase.class.getResourceAsStream("jdbc.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			Class.forName(properties.getProperty("jdbc.driver") + "");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public Connection getConnection() throws SQLException {
		if (connection == null || connection.isClosed()) {
			connection = DriverManager.getConnection(
					properties.getProperty("jdbc.url") + "",
					properties.getProperty("jdbc.user") + "",
					properties.getProperty("jdbc.pass") + "");
		}
		return connection;
	}
	
	public ResultSet doQuery(String sql) throws SQLException{
		statement = getConnection().prepareStatement(sql);
		try {
			ResultSet rs = statement.executeQuery();
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public int update(String sql) throws SQLException{
	    statement = getConnection().prepareStatement(sql);
		try {
			return statement.executeUpdate();
		} catch (Exception e) {
		}
		return 0;
	}
	
	public void close(){
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
			}
		}
	}
}












